 package com.ecart;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.hibernate.Session;

import com.ecartdb.EcartDB;
import com.ecartdb.data.Account;
import com.ecartdb.data.Item;
import com.ecartdb.data.Order;
import com.ecartdb.data.OrderItems;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
/**
 * This is a client-facing service class.  All
 * public methods will be exposed to the client.  Their return
 * values and parameters will be passed to the client or taken
 * from the client, respectively.  This will be a singleton
 * instance, shared between all requests. 
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL, String, Exception).
 * LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log level.
 * For info on these levels, look for tomcat/log4j documentation
 */
@ExposeToClient
public class OrderService extends JavaServiceSuperClass {
    /* Pass in one of FATAL, ERROR, WARN,  INFO and DEBUG to modify your log level;
     *  recommend changing this to FATAL or ERROR before deploying.  For info on these levels, look for tomcat/log4j documentation
     */
    public OrderService() {
       super(INFO);
    }

    public String placeOrder(OrderDetails order) {
       String result  = null;
     
		EcartDB db = (EcartDB) RuntimeAccess.getInstance().getServiceBean("ecartDB");
	/*	MailSenderService mailsend = (MailSenderService) RuntimeAccess
				.getInstance().getServiceBean("MailSenderService");
*/
		try {
			  System.out.println("order=="+order.getComment());
		       System.out.println("quantity=="+order.getItems().get(0).getQuantity());
		     
			System.out.println("customerId=" + order.getCustomerId());

			db.begin();

			Session session = db.getDataServiceManager().getSession();

		//	Customer vendor = (Customer) session.get(Customer.class, vendorId);
			Account customer = (Account) session.get(Account.class,	order.getCustomerId());

			
			Order customerOrder = new Order();
			//customerOrder.setProject(customer.getProject());
			//customerOrder.setCustomerByCustomerId(customer);
			customerOrder.setAccountByAccountId(customer);
		//	customerOrder.setCustomerByVendorId(vendor);
			Calendar startingCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
		
			customerOrder.setOrderDt(startingCalendar.getTime());
			customerOrder.setUpdatedBy(customer.getEmail());
			//customerOrder.setAddress(address);
			customerOrder.setStatus("NEW");
			customerOrder.setActive(true);
			customerOrder.setComments(order.getComment());
			customerOrder.setContactNum(customer.getCellPhone());
			session.save(customerOrder);
			Float price = 0f;
			String orderDetails = "";
			for (Item od : order.getItems()) {
				if (od.getQuantity() != null && od.getQuantity().intValue() > 0) {

					OrderItems orderItem = new OrderItems();
					Item item = (Item) session.get(Item.class,
							od.getItemId());

					orderItem.setOrder(customerOrder);
					orderItem.setQuantity(new BigDecimal(od.getQuantity().toString()));
					float itemTotalPrice = od.getItemPrice().floatValue()
							* od.getQuantity().floatValue();
					orderItem.setPrice(new BigDecimal(itemTotalPrice));
					orderItem.setStatus("NEW");
					orderItem.setItem(item);
					customerOrder.getOrderItemses().add(orderItem);
					session.save(orderItem);

					orderDetails = orderDetails + " " + item.getItemName()
							+ " - " + od.getQuantity();

					price += itemTotalPrice;
				}
			}
			customerOrder.setTotalPrice(new BigDecimal(price));
			session.saveOrUpdate(customerOrder);

			db.commit();
			log(INFO, "Order created successfully: Order number is:"
					+ customerOrder.getOrderId() + ";Customer Id,email="
					+ customer.getAccountId() + "&" + customer.getEmail());
				//	+ ";VendorName=" + vendor.getName());

			result = "Your Last Order# "
					+ customerOrder.getOrderId()
					+ " and Total Price is "
					+ customerOrder.getTotalPrice().floatValue()
					+ " Rs.</br>";
				/*	+ (vendor.getVendor_msg() == null ? "" : vendor
							.getVendor_msg());*/
			orderDetails = orderDetails + " and Total Price is "
					+ customerOrder.getTotalPrice().floatValue() + " Rs.";
			// SMSService smsService = new SMSService();
			//ManageOrderService smsService = (ManageOrderService) RuntimeAccess
			//		.getInstance().getServiceBean("OrderManageService");

		/*	String sMessage = smsService.ConstructTemplate("",
					customer.getFirstName(), customer.getAddress(),
					customer.getCellPhone(),
					customerOrder.getOrderId() + "", blockName, doorName,
					orderDetails);*/

			/*String response = smsService.SMSSender(
					"91" + vendor.getPrimaryPhone(), sMessage);
			System.out.println(response);
*/
			log(INFO, "sending vendor email" + customerOrder.getOrderId()
					+ ";Customer Id,email=" + customer.getAccountId() + "&"
					+ customer.getEmail() );

		/*	mailsend.sendEmailToVendor(String.valueOf(customerOrder
					.getOrderId()));*/

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());
			result = "Error during order creation,Please try again";
			log(ERROR, "Error during placing oreder:", e);
		}

		return result;
    }
    public static class OrderDetails {

		private Integer customerId;
		private String comment;

		private List<Item> items;

		private Integer vendorId;

		public Integer getCustomerId() {
			return customerId;
		}

		public String getComment() {
			return comment;
		}

		public void setComment(String comment) {
			this.comment = comment;
		}

		public void setCustomerId(Integer customerId) {
			this.customerId = customerId;
		}

		public Integer getVendorId() {
			return vendorId;
		}

		public void setVendorId(Integer vendorId) {
			this.vendorId = vendorId;
		}

		public List<Item> getItems() {
			return items;
		}

		public void setItems(List<Item> items) {
			this.items = items;
		}

		

	}
    

}
